import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLineEdit, QPushButton, QLabel
from PySide6.QtGui import QIcon

class BackupToolWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 设置窗体大小、标题和图标
        self.setWindowTitle("小白输入法数据备份工具")
        self.setWindowIcon(QIcon("ico/xiaobait9.ico"))
        self.resize(320, 185)

        # 创建中心部件和布局
        central_widget = QWidget()
        main_layout = QVBoxLayout(central_widget)

        # 添加文本1
        text1 = QLabel("1. 选择小白输入法的安装路径：")
        main_layout.addWidget(text1)

        # 创建水平布局1，用于摆放文本框和选择按钮
        layout1 = QHBoxLayout()
        self.text_input = QLineEdit()
        self.text_input.setPlaceholderText("请选择小白输入法的安装目录")
        self.select_button = QPushButton("选择")

        # 设置控件比例
        layout1.addWidget(self.text_input, 5)
        layout1.addWidget(self.select_button, 1)

        # 将布局添加到主布局
        main_layout.addLayout(layout1)

        # 添加文本2
        text2 = QLabel("2. 选择你要进行的操作：")
        main_layout.addWidget(text2)

        # 创建水平布局2，用于摆放备份和还原按钮
        layout2 = QHBoxLayout()
        self.backup_button = QPushButton("备份资料")
        restore_button = QPushButton("还原资料")

        # 设置控件比例
        layout2.addWidget(self.backup_button, 1)
        layout2.addWidget(restore_button, 1)

        # 将布局添加到主布局
        main_layout.addLayout(layout2)

        # 设置中心部件
        self.setCentralWidget(central_widget)


        # 连接信号与槽函数
        self.setup_connections()

    def setup_connections(self):
        """ 连接按钮点击信号与槽函数 """
        from PySide6.QtWidgets import QFileDialog
        from PySide6.QtWidgets import QFileDialog, QMessageBox
        import os
        import shutil
        import tempfile
        from datetime import datetime
        import subprocess

        # 文件选择按钮点击事件
        def select_directory():
            dir_path = QFileDialog.getExistingDirectory(
                self,
                "选择小白输入法安装目录",
                r"C:\Program Files (x86)\xiaobait9",  # 默认到小白的安装目录，一步到位。
                QFileDialog.ShowDirsOnly
            )
            if dir_path:
                self.text_input.setText(dir_path)

        self.select_button.clicked.connect(select_directory)

        def backup_data():
            # 获取输入目录
            install_dir = self.text_input.text()
            data_dir = os.path.join(install_dir, "data")

            # 初始化变量，防止报错
            data_back = user_back = None

            if not os.path.exists(data_dir):
                QMessageBox.critical(self, "错误", "指定目录下未找到data文件夹")
                return

            try:
                # 创建临时目录
                temp_dir = tempfile.gettempdir()
                date_str = datetime.now().strftime("%Y_%m_%d")

                # 检查data目录是否存在且非空
                if not os.path.exists(data_dir) or not os.listdir(data_dir):
                    raise Exception("data目录不存在或为空")

                # 压缩安装目录的data文件夹
                data_back = os.path.join(temp_dir, "data")
                subprocess.run(
                    ["tar", "-czf", data_back, "-C", os.path.dirname(data_dir), "data"],
                    check=True,
                    stderr=subprocess.PIPE
                )

                # 压缩用户配置目录
                user_dir = os.path.expandvars(r"%USERPROFILE%\AppData\Roaming\Rime")
                user_back = os.path.join(temp_dir, "user")
                subprocess.run(
                    ["tar", "-czf", user_back, "-C", os.path.dirname(user_dir), "Rime"],
                    check=True,
                    stderr=subprocess.PIPE
                )

                # 弹出保存对话框
                save_path, _ = QFileDialog.getSaveFileName(
                    self,
                    "保存备份文件",
                    os.path.expandvars(f"%USERPROFILE%\\xiaobai_{date_str}.back.tar.gz"),
                    "TAR.GZ压缩文件 (*.tar.gz)"
                )

                if save_path:
                    # 合并两个备份文件
                    with open(save_path, "wb") as f:
                        for fname in [data_back + ".tar.gz", user_back + ".tar.gz"]:
                            with open(fname, "rb") as src:
                                shutil.copyfileobj(src, f)

                    QMessageBox.information(self, "完成", "备份文件已保存至：" + save_path)

            except subprocess.CalledProcessError as e:
                err_msg = f"压缩失败: {e.stderr.decode('gbk').strip()}"
                QMessageBox.critical(self, "错误", err_msg)

            except Exception as e:
                QMessageBox.critical(self, "错误", f"备份过程中出现错误：{str(e)}")
            finally:
                # 清理临时文件，添加空值检查
                temp_files = []
                if data_back: temp_files.append(data_back + ".tar.gz")
                if user_back: temp_files.append(user_back + ".tar.gz")  # 修改文件扩展名

                for f in temp_files:
                    if os.path.exists(f):
                        os.remove(f)

        self.backup_button.clicked.connect(backup_data)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = BackupToolWindow()
    window.show()
    sys.exit(app.exec())
